#include <gpiod.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "record.h"
#include "control.h"
#include "snowboy/snowboy-detect-c-wrapper.h" //唤醒词检测

extern snd_pcm_t *capture; // 声明外部变量capture

#define SILENCE_THRESHOLD 0.02 // 静音检测阈值
#define SILENCE_DURATION 5 // 静音持续时间（秒）

int main() {
    // 创建snowboy检测器
    SnowboyDetect* detector = SnowboyDetectConstructor("common.res", "wakeup.pmdl");

    if (!detector) {
        return EXIT_FAILURE;
    }

    // 获取采样参数
    int bits = SnowboyDetectBitsPerSample(detector);
    int channels = SnowboyDetectNumChannels(detector);
    int rate = SnowboyDetectSampleRate(detector);
    snd_pcm_uframes_t period = 999; // 设置周期大小

    printf("采样深度:%d\n", bits);
    printf("声道数量:%d\n", channels);
    printf("采样频率:%d\n", rate);

    // 打开音频采集设备
    int err = open_pcm_device(&capture, "hw:0,0", SND_PCM_FORMAT_S16_LE, rate, channels, period);
    if (err < 0) {
        return EXIT_FAILURE;
    }

    SnowboyDetectSetSensitivity(detector, "0.5");

    char* buffer = malloc(snd_pcm_frames_to_bytes(capture, period));
    if (!buffer) {
        perror("malloc");
        snd_pcm_close(capture);
        SnowboyDetectDestructor(detector);
        return EXIT_FAILURE;
    }

    int recording_started = 0;
    int silence_counter = 0;

    while (1) {
        snd_pcm_sframes_t frames = snd_pcm_readi(capture, buffer, period);
        if (frames < 0) {
            fprintf(stderr, "读取音频帧失败：%s\n", snd_strerror(frames));
            snd_pcm_recover(capture, frames, 0);
            continue;
        }

        // 唤醒词检测
        int status = SnowboyDetectRunDetection(detector, (int16_t*)buffer, frames * channels, 0);
        if (status > 0) {
            printf("检测到唤醒词\n");
            if (!recording_started) {
                err = start_recording("output.pcm", period, channels);
                if (err < 0) {
                    free(buffer);
                    snd_pcm_close(capture);
                    SnowboyDetectDestructor(detector);
                    return EXIT_FAILURE;
                }
                recording_started = 1;
                silence_counter = 0;
            }
        }

        if (recording_started) {
            handle_recording(period);

            // 静音检测
            int16_t* samples = (int16_t*)buffer;
            int silence_samples = 0;
            for (int i = 0; i < frames * channels; ++i) {
                if (abs(samples[i]) < SILENCE_THRESHOLD * INT16_MAX) {
                    silence_samples++;
                }
            }
            if (silence_samples >= frames * channels * 0.9) { // 超过90%的样本为静音
                silence_counter++;
            } else {
                silence_counter = 0;
            }

            if (silence_counter >= SILENCE_DURATION * rate / period) {
                printf("检测到连续5秒的静音，停止录音\n");
                stop_recording();
                recording_started = 0;
                break; // 录音停止，跳出循环
            }
        }
    }

    free(buffer);
    if (recording_started) {
        stop_recording();
    }
    SnowboyDetectDestructor(detector);

    return EXIT_SUCCESS;
}
